/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.hva.bluepumpkin.server.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import vn.hva.bluepumpkin.common.dto.UserProfileDTO;
import vn.hva.bluepumpkin.ejb.session.user.ManageUserRemoteHome;
import vn.hva.bluepumpkin.common.util.ServiceLocator;
import vn.hva.bluepumpkin.ejb.session.user.ManageUserRemote;

/**
 *
 * @author USER
 */
public class UploadImage extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        response.setHeader("Cache-control", "no-cache");

        String err = "";
        String lastFileName = "";

        String huserid = request.getParameter("huserid");
        System.out.println("==============================" + huserid);
        String contentType = request.getContentType();
        String boundary = "";
        final int BOUNDARY_WORD_SIZE = "boundary=".length();
        if (contentType == null || !contentType.startsWith("multipart/form-data")) {
            err = "Ilegal ENCTYPE : must be multipart/form-data\n";
            err += "ENCTYPE set = " + contentType;
        } else {
            boundary = contentType.substring(contentType.indexOf("boundary=") + BOUNDARY_WORD_SIZE);
            boundary = "--" + boundary;
            try {
                javax.servlet.ServletInputStream sis = request.getInputStream();

                byte[] b = new byte[1024];
                int x = 0;
                int state = 0;
                String name = null, fileName = null, contentType2 = null;
                java.io.FileOutputStream buffer = null;
                while ((x = sis.readLine(b, 0, 1024)) > -1) {
                    String s = new String(b, 0, x);

                    if (s.startsWith(boundary)) {
                        state = 0;
                        //out.println("name="+name+"<br>");
                        //out.println(fileName+"<br>");

                        name = null;
                        contentType2 = null;
                        fileName = null;


                    } else if (s.startsWith("Content-Disposition") && state == 0) {
                        System.out.println(s.toString());
                        state = 1;
                        if (s.indexOf("filename=") == -1) {
                            name = s.substring(s.indexOf("name=") + "name=".length(), s.length() - 2);
                        } else {
                            name = s.substring(s.indexOf("name=") + "name=".length(), s.lastIndexOf(";"));
                            fileName = s.substring(s.indexOf("filename=") + "filename=".length(), s.length() - 2);
                            if (fileName.equals("\"\"")) {
                                fileName = null;
                            } else {
                                String userAgent = request.getHeader("User-Agent");
                                String userSeparator = "/";  // default
                                if (userAgent.indexOf("Windows") != -1) {
                                    userSeparator = "\\";
                                }
                                if (userAgent.indexOf("Linux") != -1) {
                                    userSeparator = "/";
                                }
                                fileName = fileName.substring(fileName.lastIndexOf(userSeparator) + 1, fileName.length() - 1);
                                if (fileName.startsWith("\"")) {
                                    fileName = fileName.substring(1);
                                }
                            }
                        }
//                        if(s.indexOf("huserid") == 1){
//                            System.out.println(s.toString());
//                        }
                        name = name.substring(1, name.length() - 1);
//                        if(name.equals("huserid")){
//                            //
//                        }
                        if (name.equals("file")) {
                            if (buffer != null) {
                                buffer.close();
                            }
                            java.util.Date date = new java.util.Date();
                            lastFileName = date.getTime() + fileName;
                            buffer = new java.io.FileOutputStream(getServletContext().getRealPath("") + "/images/avatar/" + lastFileName);
                        }
                    } else if (s.startsWith("Content-Type") && state == 1) {
                        System.out.println(String.valueOf(state) + s.toString());
                        state = 2;
                        contentType2 = s.substring(s.indexOf(":") + 2, s.length() - 2);
                    } else if (s.equals("\r\n") && state != 3) {
                        state = 3;
                    } else {
                        if (name.equals("huserid")) {
                            huserid = s.toString();
                        }
                        if (name.equals("file")) {
                            buffer.write(b, 0, x);
                        }

                    }
                }
                sis.close();
                buffer.close();
            } catch (java.io.IOException e) {
                err = e.toString();
            }
            boolean ok = err.equals("");
            if (!ok) {
                out.println(err);
            } else {
                try {
                    String imageName = lastFileName;
                    ManageUserRemoteHome home = (ManageUserRemoteHome) ServiceLocator.getEjbRemoteHome("java:ManageUserSB",
                            ManageUserRemoteHome.class);
                    ManageUserRemote remote = home.create();
                    if (huserid == null) {
                        HttpSession session = request.getSession(true);
                        UserProfileDTO upDTO = (UserProfileDTO) session.getAttribute("user");
                        int userid = upDTO.getUserid();
                        upDTO = remote.updateAvatar(userid, imageName);
                        session.setAttribute("user", upDTO);
                        response.sendRedirect(request.getContextPath() + "/pages/employee/profile.jsp");
                    } else {
                        System.out.println("User id:" + huserid.trim());
                        int userid = Integer.parseInt(huserid.trim());

                        remote.updateAvatar(userid, imageName);
                        request.setAttribute("update_avatar", "Avatar update successfully");
                        response.sendRedirect(request.getContextPath() + "/pages/admin/manageemployee.jsp");
                        //RequestDispatcher rd = request.getRequestDispatcher("/pages/admin/manageemployee.jsp");
                        //rd.forward(request, response);
                    }

                } catch (CreateException ex) {
                    ex.printStackTrace();
                } catch (RemoteException ex) {
                    ex.printStackTrace();
                } catch (NamingException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
